package cn.e3mall.service.message;

import java.util.ArrayList;
import java.util.List;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.mapper.ItemMapper;

public class ItemAddMessageListener implements MessageListener{
	
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private SolrServer solrServer;

	@Override
	public void onMessage(Message message) {
		try {
			TextMessage textMessage = (TextMessage) message;
			String text = textMessage.getText();
			if(text.indexOf("-")!=-1) {
				//当操作为(下架、删除时)
				text = text.substring(1, text.indexOf("-")-1);
				solrServer.deleteById(getStringList(text));
				solrServer.commit();
			}else if(text.indexOf("+")!=-1){
				//当操作为(批量上架时)
				text = text.substring(1, text.indexOf("+")-1);
				for(String id:getStringList(text)) {
					Long itemId = new Long(id);
					//等待事务提交
					Thread.sleep(1000);
					//根据商品id查询商品信息
					SearchItem searchItem = itemMapper.getItemById(itemId);
					//创建一个文档对象
					SolrInputDocument document = new SolrInputDocument();
					//向文档对象中添加域
					document.addField("id", searchItem.getId());
					document.addField("item_title", searchItem.getTitle());
					document.addField("item_sell_point", searchItem.getSell_point());
					document.addField("item_price", searchItem.getPrice());
					document.addField("item_image", searchItem.getImage());
					document.addField("item_category_name", searchItem.getCategory_name());
					//把文档写入索引库
					solrServer.add(document);
					//提交
					solrServer.commit();
				}
			}else {
				//当操作为(单个修改或者添加时)
				Long itemId = new Long(text);
				//等待事务提交
				Thread.sleep(1000);
				//根据商品id查询商品信息
				SearchItem searchItem = itemMapper.getItemById(itemId);
				//创建一个文档对象
				SolrInputDocument document = new SolrInputDocument();
				//向文档对象中添加域
				document.addField("id", searchItem.getId());
				document.addField("item_title", searchItem.getTitle());
				document.addField("item_sell_point", searchItem.getSell_point());
				document.addField("item_price", searchItem.getPrice());
				document.addField("item_image", searchItem.getImage());
				document.addField("item_category_name", searchItem.getCategory_name());
				//把文档写入索引库
				solrServer.add(document);
				//提交
				solrServer.commit();
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * String转List集合并且去空格
	* @Title: getStringList  
	* @Description: TODO
	* @param @param text
	* @param @return    参数  
	* @return List<String>    返回类型  
	* @throws
	 */
	public List<String> getStringList(String text) {
		List<String> ids = new ArrayList<String>();
		String[] textString = text.split(",");
		for(String uid: textString){
			ids.add(uid.trim());
		}
		return ids;
		
	}
}
